import { defineStore } from "pinia";

export const useVideoPlayerStore = defineStore("videoPlayer", {
  state: () => ({
    isModalVisible: false,
    currentVideoId: null,
    currentVideo: null,
  }),

  actions: {
    openVideoModal(videoId, videoInfo = null) {
      this.isModalVisible = true;
      this.currentVideoId = String(videoId);
      this.currentVideo = videoInfo;
    },

    closeVideoModal() {
      this.isModalVisible = false;
      this.currentVideoId = null;
      this.currentVideo = null;
    },

    updateVideoState(videoInfo) {
      // 检查是否包含完整视频信息，如果是则可能是视频切换请求
      if (videoInfo.videoObj) {
        this.switchVideo(videoInfo.id, videoInfo.videoObj);
        return;
      }
      // 检查ID是否匹配
      if (this.currentVideoId === videoInfo.id && this.currentVideo) {
        // 只更新传入的字段，保留其他字段不变
        this.currentVideo = {
          ...this.currentVideo,
          // 只更新传入的字段
          ...(videoInfo.isLiked !== undefined
            ? { isLiked: videoInfo.isLiked }
            : {}),
          ...(videoInfo.likeCount !== undefined
            ? { likeCount: videoInfo.likeCount }
            : {}),
          ...(videoInfo.favoritesCount !== undefined
            ? { favoritesCount: videoInfo.favoritesCount }
            : {}),
          ...(videoInfo.commentCount !== undefined
            ? { commentCount: videoInfo.commentCount }
            : {}),
          ...(videoInfo.isFavorited !== undefined
            ? { isFavorited: videoInfo.isFavorited }
            : {}),
          ...(videoInfo.isFollowed !== undefined
            ? { isFollowed: videoInfo.isFollowed }
            : {}),
        };
      } else if (videoInfo.id && !this.currentVideo) {
        // 如果没有当前视频数据但提供了完整信息，则设置
        this.currentVideo = videoInfo;
      }
    },

    // 在 videoPlayerStore.js 的 switchVideo 方法中
    switchVideo(videoId, videoObj) {
      console.log("Store - 开始切换视频:", {
        id: videoId,
        title: videoObj?.title,
        src: videoObj?.src || videoObj?.oss_url,
      });

      if (!videoId) {
        console.error("无效的视频ID，无法切换");
        return;
      }

      // 先更新ID和视频对象
      this.currentVideoId = String(videoId);
      this.currentVideo = {
        ...videoObj,
        id: this.currentVideoId,
        video_id: this.currentVideoId,
      };

      // 确保模态框可见
      this.isModalVisible = true;

      console.log("Store - 视频切换完成");
    },
  },
});
